<?php

//SANITIZE ALL ESCAPES
$sanitize_all_escapes = true;
//
//STOP FAKE REGISTER GLOBALS
$fake_register_globals = false;

require_once("../../globals.php");
require_once("$srcdir/patient.inc");
require_once("$srcdir/acl.inc");
require_once("$srcdir/classes/Address.class.php");
require_once("$srcdir/classes/InsuranceCompany.class.php");
require_once("$srcdir/classes/Document.class.php");
require_once("$srcdir/options.inc.php");
require_once("../history/history.inc.php");
require_once("$srcdir/formatting.inc.php");
require_once("$srcdir/edi.inc");
require_once("$srcdir/clinical_rules.php");

if (isset($_GET['set_pid'])) {
    include_once("$srcdir/pid.inc");
    setpid($_GET['set_pid']);
}

$active_reminders = false;
if ((!isset($_SESSION['alert_notify_pid']) || ($_SESSION['alert_notify_pid'] != $pid)) && isset($_GET['set_pid']) && acl_check('patients', 'med') && $GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_crp']) {
    // showing a new patient, so check for active reminders
    $active_reminders = active_alert_summary($pid, "reminders-due");
}

function pic_array() {
    $imagedir = $GLOBALS['OE_SITE_DIR'] . "/documents/$pid/demographics";
    $imagepath = "$web_root/sites/" . $_SESSION['site_id'] . "/documents/$pid/demographics";

    $picture_directory = "Patient Photograph"; //change this if you want
    $pics = array();
    $sql_query = "select documents.id from documents join categories_to_documents on documents.id = categories_to_documents.document_id join categories on categories.id = categories_to_documents.category_id where categories.name like ? and documents.foreign_id = ?";
    if ($query = sqlStatement($sql_query, array($picture_directory, $_SESSION['pid']))) {
        $results = sqlFetchArray($query);

        if (count($results) > 0) {
            /* echo "<pre>";
              print_r($results);
              echo "</pre>";die;
              <img src='$imagepath/photo.jpg' />
             */

            $tmp = $results['id'];
            if (isset($tmp)) {
                array_push($pics, "<div id='photograph' class='patient_pic'><img width='100px' height='100px' src='" . $GLOBALS['webroot'] . "/controller.php?document&retrieve&patient_id=" . htmlspecialchars($_SESSION['pid'], ENT_QUOTES) . "&document_id=" . htmlspecialchars($tmp, ENT_QUOTES) . "&as_file=false' alt='Foto'></div>\n");
            } else {
                array_push($pics, "<div id='photograph' class='patient_pic'><img width='100px' src='../../../images/patient.png' alt='Foto'></div>\n");

				 /*array_push($pics, "<div id='photograph' class='patient_pic'><a href='' onclick=\"return sendimage(" . $_SESSION['pid'] . ", 'photo');\" " . "title='Click para agregar la foto del paciente'><img width='100px' src='../../../images/patient.png' alt='Foto'></a></div>\n");*/
				
                //---Huella digital
                /*
                  $imagedir  = $GLOBALS['OE_SITE_DIR'] . "/documents/$pid/demographics";
                  $imagepath = "$web_root/sites/" . $_SESSION['site_id'] . "/documents/$pid/demographics";
                  echo "   <a href='' onclick=\"return sendimage($pid, 'fingerprint');\" " .
                  "title='Click to attach fingerprint'>\n";
                  if (is_file("$imagedir/fingerprint.jpg")) {
                  echo "   <img src='$imagepath/fingerprint.jpg' /></a>\n";
                  } else {
                  echo "   Attach Biometric Fingerprint</a><br />\n";
                  }
                  echo "   <br />&nbsp;<br />\n"; */
            }
        } else {
            array_push($pics, "<div id='photograph' class='patient_pic'><img height='88px' src='../../../images/patient.png' alt='Foto'></div>\n");
        }
    }
    return $pics;
}

function print_as_money($money) {
    preg_match("/(\d*)\.?(\d*)/", $money, $moneymatches);
    $tmp = wordwrap(strrev($moneymatches[1]), 3, ",", 1);
    $ccheck = strrev($tmp);
    if ($ccheck[0] == ",") {
        $tmp = substr($ccheck, 1, strlen($ccheck) - 1);
    }
    if ($moneymatches[2] != "") {
        return "$ " . strrev($tmp) . "." . $moneymatches[2];
    } else {
        return "$ " . strrev($tmp);
    }
}

function get_document_by_catg($pid, $doc_catg) {

    $result = array();

    if ($pid and $doc_catg) {
        $result = sqlQuery("SELECT d.id, d.date, d.url FROM " .
                "documents AS d, categories_to_documents AS cd, categories AS c " .
                "WHERE d.foreign_id = ? " .
                "AND cd.document_id = d.id " .
                "AND c.id = cd.category_id " .
                "AND c.name LIKE ? " .
                "ORDER BY d.date DESC LIMIT 1", array($pid, $doc_catg));
    }

    return($result['id']);
}

// Display image in 'widget style'
function image_widget($doc_id, $doc_catg) {
    global $pid, $web_root;
    $docobj = new Document($doc_id);
    $image_file = $docobj->get_url_file();
    $extension = substr($image_file, strrpos($image_file, "."));
    $viewable_types = array('.png', '.jpg', '.jpeg', '.png', '.bmp', '.PNG', '.JPG', '.JPEG', '.PNG', '.BMP'); // image ext supported by fancybox viewer
    if (in_array($extension, $viewable_types)) { // extention matches list
        $to_url = "<td> <a href = $web_root" .
                "/controller.php?document&retrieve&patient_id=$pid&document_id=$doc_id" .
                "/tmp$extension" . // Force image type URL for fancybox
                " onclick=top.restoreSession(); class='image_modal'>" .
                " <img src = $web_root" .
                "/controller.php?document&retrieve&patient_id=$pid&document_id=$doc_id" .
                " width=100 alt='$doc_catg:$image_file'>  </a> </td> <td valign='center'>" .
                htmlspecialchars($doc_catg) . '<br />&nbsp;' . htmlspecialchars($image_file) .
                "</td>";
    } else {
        $to_url = "<td> <a href='" . $web_root . "/controller.php?document&retrieve" .
                "&patient_id=$pid&document_id=$doc_id'" .
                " onclick='top.restoreSession()' class='css_button_small'>" .
                "<span>" .
                htmlspecialchars(xl("View"), ENT_QUOTES) . "</a> &nbsp;" .
                htmlspecialchars("$doc_catg - $image_file", ENT_QUOTES) .
                "</span> </td>";
    }
    echo "<table><tr>";
    echo $to_url;
    echo "</tr></table>";
}

// Determine if the Vitals form is in use for this site.
$tmp = sqlQuery("SELECT count(*) AS count FROM registry WHERE " .
        "directory = 'vitals' AND state = 1");
$vitals_is_registered = $tmp['count'];

// Get patient/employer/insurance information.
//
$result = getPatientData($pid, "*, DATE_FORMAT(DOB,'%Y-%m-%d') as DOB_YMD");
$result2 = getEmployerData($pid);
$result3 = getInsuranceData($pid, "primary", "copay, provider, DATE_FORMAT(`date`,'%Y-%m-%d') as effdate");
$insco_name = "";
if ($result3['provider']) {   // Use provider in case there is an ins record w/ unassigned insco
    $insco_name = getInsuranceProvider($result3['provider']);
}
?>
<html>

    <head>
        <!-- Add jQuery library -->
        <script type="text/javascript" src="../../../library/js/jquery-1.9.1.min.js"></script>
        <!-- Add fancyBox main JS and CSS files -->
        <script type="text/javascript" src="../../../library/js/jquery-ui-1.7.custom.min.js"></script>
        <script type="text/javascript" src="../../../library/js/common.js"></script>
        <script type="text/javascript" src="../../../library/js/jquery.fancybox.pack.js"></script>
        <link rel="stylesheet" type="text/css" href="/interface/themes/jquery.fancybox.css?v=2.1.5" media="screen"/>
        <link rel="stylesheet" type="text/css" href="/interface/themes/jquery-accordion.css" >

        <script type="text/javascript" src="../../../library/js/jquery-accordion.js"></script>
        <style type="text/css">@import url(../../../library/dynarch_calendar.css);</style>
        <script type="text/javascript" src="../../../library/textformat.js"></script>
        <script type="text/javascript" src="../../../library/dynarch_calendar.js"></script>
        <?php include_once("{$GLOBALS['srcdir']}/dynarch_calendar_en.inc.php"); ?>
        <script type="text/javascript" src="../../../library/dynarch_calendar_setup.js"></script>

        <script type="text/javascript" language="JavaScript">

            var mypcc = '<?php echo htmlspecialchars($GLOBALS['phone_country_code'], ENT_QUOTES); ?>';

            function oldEvt(eventid) {
                dlgopen('../../main/calendar/add_edit_event.php?eid=' + eventid, '_blank', 550, 350);
            }

            function advdirconfigure() {
                dlgopen('advancedirectives.php', '_blank', 500, 450);
            }

            function refreshme() {
                top.restoreSession();
            }

            // Process click on Delete link.
            function deleteme() {
                dlgopen('../deleter.php?patient=<?php echo htmlspecialchars($pid, ENT_QUOTES); ?>', '_blank', 500, 450);
                return false;
            }

            // Called by the deleteme.php window on a successful delete.
            function imdeleted() {
<?php if ($GLOBALS['concurrent_layout']) { ?>
                    parent.left_nav.clearPatient();
<?php } else { ?>
                    top.restoreSession();
                    top.location.href = '../main/main_screen.php';
<?php } ?>
            }

            function validate() {
                var f = document.forms[0];
<?php
if ($GLOBALS['athletic_team']) {
    echo "  if (f.form_userdate1.value != f.form_original_userdate1.value) {\n";
    $irow = sqlQuery("SELECT id, title FROM lists WHERE " .
            "pid = ? AND enddate IS NULL ORDER BY begdate DESC LIMIT 1", array($pid));
    if (!empty($irow)) {
        ?>
                        if (confirm('Do you wish to also set this new return date in the issue titled "<?php echo htmlspecialchars($irow['title'], ENT_QUOTES); ?>"?')) {
                            f.form_issue_id.value = '<?php echo htmlspecialchars($irow['id'], ENT_QUOTES); ?>';
                        } else {
                            alert('OK, you will need to manually update the return date in any affected issue(s).');
                        }
    <?php } else { ?>
                        alert('You have changed the return date but there are no open issues. You probably need to create or modify one.');
        <?php
    } // end empty $irow
    echo "  }\n";
} // end athletic team
?>
                return true;
            }

            function newEvt() {
                dlgopen('appointments', '../main/calendar/add_edit_event.php?patientid=<?php echo htmlspecialchars($pid, ENT_QUOTES); ?>', '_blank', 700, 380);
                return false;
            }

            function sendimage(pid, what) {
                // alert('Not yet implemented.'); return false;
                /*dlgopen('../upload_dialog.php?patientid=' + pid + '&file=' + what,
                 '_blank', 500, 400);
                 */
                dlgopen('http://ginecologia.saludaunclic.com/controller.php?document&upload&patient_id=' + pid + '&parent_id=4',
                        '_blank', 650, 450);


                return false;
            }

        </script>

        <script type="text/javascript">

            function toggleIndicator(target, div) {

                $mode = $(target).find(".indicator").text();
                if ($mode == "<?php echo htmlspecialchars(xl('collapse'), ENT_QUOTES); ?>") {
                    $(target).find(".indicator").text("<?php echo htmlspecialchars(xl('expand'), ENT_QUOTES); ?>");
                    $("#" + div).hide();
                    $.post("../../../library/ajax/user_settings.php", {target: div, mode: 0});
                } else {
                    $(target).find(".indicator").text("<?php echo htmlspecialchars(xl('collapse'), ENT_QUOTES); ?>");
                    $("#" + div).show();
                    $.post("../../../library/ajax/user_settings.php", {target: div, mode: 1});
                }
            }

            $(document).ready(function() {

                //timeline
                $("#eventos").load("../patient_file/summary/get_encounters.php");

                var msg_updation = '';
<?php
if ($GLOBALS['erx_enable']) {
    //$soap_status=sqlQuery("select soap_import_status from patient_data where pid=?",array($pid));
    $soap_status = sqlStatement("select soap_import_status,pid from patient_data where pid=? and soap_import_status in ('1','3')", array($pid));
    while ($row_soapstatus = sqlFetchArray($soap_status)) {
        //if($soap_status['soap_import_status']=='1' || $soap_status['soap_import_status']=='3'){ 
        ?>
                        top.restoreSession();
                        $.ajax({
                            type: "POST",
                            url: "../../soap_functions/soap_patientfullmedication.php",
                            dataType: "html",
                            data: {
                                patient:<?php echo $row_soapstatus['pid']; ?>,
                            },
                            async: false,
                            success: function(thedata) {
                                //alert(thedata);
                                msg_updation += thedata;
                            },
                            error: function() {
                                alert('ajax error');
                            }
                        });
        <?php
        //}	
        //elseif($soap_status['soap_import_status']=='3'){ 
        ?>
                        top.restoreSession();
                        $.ajax({
                            type: "POST",
                            url: "../../soap_functions/soap_allergy.php",
                            dataType: "html",
                            data: {
                                patient:<?php echo $row_soapstatus['pid']; ?>,
                            },
                            async: false,
                            success: function(thedata) {
                                //alert(thedata);
                                msg_updation += thedata;
                            },
                            error: function() {
                                alert('ajax error');
                            }
                        });
        <?php if ($GLOBALS['erx_import_status_message']) { ?>
                            if (msg_updation)
                                alert(msg_updation);
            <?php
        }
        //} 
    }
}
?>

                //Problemas medicos, alergias, medicamentos y vacunaciones
                $("#stats_div").load("../patient_file/summary/stats.php", function() {
                    $('.iframe_stats').click(function(e) {
                        e.preventDefault();
                        $.fancybox({
                            href: this.href,
                            autoSize: true,
                            type: 'iframe',
                            helpers: {
                                overlay: {
                                    opacity: 0.3,
                                    css: {
                                        'background': 'rgba(255, 254, 254,0.85)'
                                    }
                                } // overlay
                            } // helpers
                        }); // fancybox
                    }); // click 	
                });

                //Notas
                $("#pnotes_ps_expand").load("../patient_file/summary/pnotes_fragment.php");

                //Publicaciones
                $("#disclosures_ps_expand").load("../patient_file/summary/disc_fragment.php");

<?php if ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_crw']) { ?>
                    $("#clinical_reminders_ps_expand").load("../patient_file/summary/clinical_reminders_fragment.php", function() {
                        $('.iframe_reminders').click(function(e) {
                            e.preventDefault();
                            parent.$.fancybox({
                                href: this.href,
                                autoSize: true,
                                type: 'iframe',
                                helpers: {
                                    overlay: {
                                        opacity: 0.3,
                                        css: {
                                            'background': 'rgba(255, 254, 254,0.85)'
                                        }
                                    } // overlay
                                } // helpers
                            }); // fancybox
                        }); // click 	
                    });
<?php } // end crw   ?>

                //Recordatorios del paciente
<?php if ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_prw']) { ?>
                    $("#patient_reminders_ps_expand").load("../patient_file/summary/patient_reminders_fragment.php");
<?php } // end prw   ?>

                //Constantes vitales
<?php if ($vitals_is_registered && acl_check('patients', 'med')) { ?>
                    $("#vitals_ps_expand").load("../patient_file/summary/vitals_fragment.php");
<?php } ?>

<?php
// Initialize for each applicable LBF form.
$gfres = sqlStatement("SELECT option_id FROM list_options WHERE " .
        "list_id = 'lbfnames' AND option_value > 0 ORDER BY seq, title");
while ($gfrow = sqlFetchArray($gfres)) {
    ?>
                    $("#<?php echo $gfrow['option_id']; ?>_ps_expand").load("../patient_file/summary/lbf_fragment.php?formname=<?php echo $gfrow['option_id']; ?>");
    <?php
}
?>

                //Inicializa los tabs
                tabbify();

<?php if ($active_reminders) { ?>
                    // show the active reminder modal
                    $("#reminder_popup_link").fancybox({
                        'overlayOpacity': 0.0,
                        'showCloseButton': true,
                        'frameHeight': 500,
                        'frameWidth': 500,
                        'centerOnScroll': false
                    }).trigger('click');
<?php } ?>

                $("#accordion").jqueryAccordion({
                    interval: 400,
                    fadeContent: true,
                    open: true,
                    defaultOpenIndex: 1
                });

                $('.iframe').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        autoSize: false,
                        type: 'iframe',
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        } // helpers
                    }); // fancybox
                }); // click 	
            });

            // JavaScript stuff to do when a new patient is set.
            //
            function setMyPatient() {
<?php if ($GLOBALS['concurrent_layout']) { ?>
                    // Avoid race conditions with loading of the left_nav or Title frame.
                    if (!parent.allFramesLoaded()) {
                        setTimeout("setMyPatient()", 500);
                        return;
                    }
    <?php if (isset($_GET['set_pid'])) { ?>
                        parent.left_nav.setPatient(<?php
        echo "'" . htmlspecialchars(($result['fname']) . " " . ($result['lname']), ENT_QUOTES) .
        "'," . htmlspecialchars($pid, ENT_QUOTES) . ",'" . htmlspecialchars(($result['pubpid']), ENT_QUOTES) .
        "','', ' " . htmlspecialchars(xl('DOB') . ": " . oeFormatShortDate($result['DOB_YMD']) . " " . xl('Age') . ": " . getPatientAge($result['DOB_YMD']), ENT_QUOTES) . "'";
        ?>);
                        var EncounterDateArray = new Array;
                        var CalendarCategoryArray = new Array;
                        var EncounterIdArray = new Array;
                        var Count = 0;
        <?php
        //Encounter details are stored to javacript as array.
        $result4 = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
                " left join openemr_postcalendar_categories on fe.pc_catid=openemr_postcalendar_categories.pc_catid  WHERE fe.pid = ? order by fe.date desc", array($pid));
        if (sqlNumRows($result4) > 0) {
            while ($rowresult4 = sqlFetchArray($result4)) {
                ?>
                                EncounterIdArray[Count] = '<?php echo htmlspecialchars($rowresult4['encounter'], ENT_QUOTES); ?>';
                                EncounterDateArray[Count] = '<?php echo htmlspecialchars(oeFormatShortDate(date("Y-m-d", strtotime($rowresult4['date']))), ENT_QUOTES); ?>';
                                CalendarCategoryArray[Count] = '<?php echo htmlspecialchars(xl_appt_category($rowresult4['pc_catname']), ENT_QUOTES); ?>';
                                Count++;
                <?php
            }
        }
        ?>
                        parent.left_nav.setPatientEncounter(EncounterIdArray, EncounterDateArray, CalendarCategoryArray);
    <?php } // end setting new pid    ?>
                    parent.left_nav.setRadio(window.name, 'dem');
                    parent.left_nav.syncRadios();
<?php } // end concurrent layout    ?>
            }

            $(window).load(function() {
                setMyPatient();
            });

        </script>

        <style type="css/text">
            #pnotes_ps_expand {
                height:auto;
                width:100%;
            }
        </style>

    </head>

    <body class="body_top">
        <div id="main">
            <a href='../reminder/active_reminder_popup.php' id='reminder_popup_link' style='visibility: false;' class='iframe'></a>

            <?php
            $thisauth = acl_check('patients', 'demo');
            if ($thisauth) {
                if ($result['squad'] && !acl_check('squads', $result['squad']))
                    $thisauth = 0;
            }

            if (!$thisauth) {
                echo "<p>(" . htmlspecialchars(xl('Demographics not authorized'), ENT_NOQUOTES) . ")</p>\n";
                echo "</body>\n</html>\n";
                exit();
            }
            ?>
            <div id="main_toolbar">
                <p>	
                    <?php
                    if ($thisauth) {
                        echo "<span id='welcome'>Expediente: " . htmlspecialchars(getPatientName($pid), ENT_NOQUOTES) . "</span>";

                        echo "<span style='float: right;'>";
	
                        //Btn borrar paciente
                        if (acl_check('admin', 'super')) {
                            echo "<a class='css_button iframe' title='" . htmlspecialchars(xl('Delete'), ENT_NOQUOTES) . "' href='../patient_file/deleter.php?patient=" .
                            htmlspecialchars($pid, ENT_QUOTES) . "'>" .
                            "<i class='icon-remove'></i></a>";
                        }

                        if ($GLOBALS['erx_enable']) {
                            echo '<a class="css_button" href="../../eRx.php?page=medentry" onclick="top.restoreSession()">';
                            echo "<span>" . htmlspecialchars(xl('NewCrop MedEntry'), ENT_NOQUOTES) . "</span></a>";
                            echo '<a class="css_button iframe1" href="../../soap_functions/soap_accountStatusDetails.php" onclick="top.restoreSession()">';
                            echo "<span>" . htmlspecialchars(xl('NewCrop Account Status'), ENT_NOQUOTES) . "</span></a><td id='accountstatus'></td>";
                        }

                        //Btn Patient Portal
                        $portalUserSetting = true; //flag to see if patient has authorized access to portal
                        if ($GLOBALS['portal_onsite_enable'] && $GLOBALS['portal_onsite_address']) {
                            $portalStatus = sqlQuery("SELECT allow_patient_portal FROM patient_data WHERE pid=?", array($pid));
                            if ($portalStatus['allow_patient_portal'] == 'YES') {
                                $portalLogin = sqlQuery("SELECT pid FROM `patient_access_onsite` WHERE `pid`=?", array($pid));
                                echo "<a class='css_button iframe' title='" . htmlspecialchars(xl('Reset Onsite Portal Credentials'), ENT_NOQUOTES) . "' href='../patient_file/summary/create_portallogin.php?portalsite=on&patient=" . htmlspecialchars($pid, ENT_QUOTES) . "'>";
                                echo "<i class='icon-globe'></i></a>";
                            } else {
                                $portalUserSetting = false;
                            }
                        }
						
						//Btn docs
						 echo "<a class='css_button iframe' title='" . htmlspecialchars(xl('Documents'), ENT_NOQUOTES) . "' href='../../../controller.php?document&list&patient_id=" . htmlspecialchars($pid, ENT_QUOTES) . "'>";
                         echo "<i class='icon-file-text'></i></a>";
												
                        if (!($portalUserSetting)) {
                            // Show that the patient has not authorized portal access
                            echo htmlspecialchars(xl('Patient has not authorized the Patient Portal.'), ENT_NOQUOTES);
                        }
                        //Patient Portal
                        // If patient is deceased, then show this (along with the number of days patient has been deceased for)
                        $days_deceased = is_patient_deceased($pid);
                        if ($days_deceased) {
                            echo "<td style='padding-left:1em;font-weight:bold;color:red'>" . htmlspecialchars(xl('DECEASED'), ENT_NOQUOTES) . " (" . htmlspecialchars($days_deceased, ENT_NOQUOTES) . " " . htmlspecialchars(xl('days ago'), ENT_NOQUOTES) . ")</td>";
                        }

                        echo "</span>";
                    }

                    // Get the document ID of the patient ID card if access to it is wanted here.
                    $idcard_doc_id = false;
                    if ($GLOBALS['patient_id_category_name']) {
                        $idcard_doc_id = get_document_by_catg($pid, $GLOBALS['patient_id_category_name']);
                    }
                    ?>
                </p>
            </div> 
            <!-- main_toolbar -->
            <!--
			<table cellspacing='0' cellpadding='0' border='0'>
                <tr>
                    <td class="small" colspan='4'>
                        <a href="../history/history.php" onclick='top.restoreSession()'>
                            <?php echo htmlspecialchars(xl('History'), ENT_NOQUOTES); ?></a>
                        |
                        <?php //note that we have temporarily removed report screen from the modal view  ?>
                        <a href="../report/patient_report.php" onclick='top.restoreSession()'>
                            <?php echo htmlspecialchars(xl('Report'), ENT_NOQUOTES); ?></a>
                        |
                        <?php //note that we have temporarily removed document screen from the modal view  ?>
                        <a href="../../../controller.php?document&list&patient_id=<?php echo $pid; ?>" onclick='top.restoreSession()'>
                            <?php echo htmlspecialchars(xl('Documents'), ENT_NOQUOTES); ?></a>
                        |
                        <a href="../transaction/transactions.php" class='iframe large_modal' onclick='top.restoreSession()'>
                            <?php echo htmlspecialchars(xl('Transactions'), ENT_NOQUOTES); ?></a>
                        |
                        <a href="stats_full.php?active=all" onclick='top.restoreSession()'>
                            <?php echo htmlspecialchars(xl('Issues'), ENT_NOQUOTES); ?></a>
                    </td>
                </tr>
            </table> 
			-->
			<!-- end header -->

            <div style='margin-top:10px'> <!-- start main content div -->
                <!-- start left column div -->
                <div id="column_left">
                    <!-- Timeline -->
                    <div id="eventos" class="wrapper_clinico_meds"></div> 

                    <!-- start accordion div -->
                    <div id="accordion" class="accordion">	
                        <!--Datos demograficos-->
                        <div class="accordion-item">
                            <?php
                            $widgetTitle = xl("Demographics");
                            $widgetLabel = "demographics";
                            $icon = "icon-info-sign";
                            $widgetButtonLabel = xl("Edit");
                            $widgetButtonLink = "../patient_file/summary/demographics_full.php";
                            $widgetButtonClass = "iframe";
                            $linkMethod = "html";
                            $bodyClass = "";
                            $widgetAuth = ($thisauth == "write");
                            $fixedWidth = true;
                            expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);
                            ?>
                            <div id="DEM" >
                                <ul class="tabNav"><?php display_layout_tabs('DEM', $result, $result2); ?></ul>
                                <div class="tabContainer"><?php display_layout_tabs_data('DEM', $result, $result2); ?></div>
                            </div>
                        </div> 
                    </div>

                    <!--///////////////////////////////// START INSURANCE SECTION-->
                    <?php
                    $insurance_count = 0;
                    foreach (array('primary', 'secondary', 'tertiary') as $instype) {
                        $enddate = 'Present';
                        $query = "SELECT * FROM insurance_data WHERE " .
                                "pid = ? AND type = ? " .
                                "ORDER BY date DESC";
                        $res = sqlStatement($query, array($pid, $instype));
                        while ($row = sqlFetchArray($res)) {
                            if ($row['provider'])
                                $insurance_count++;
                        }
                    }

                    if ($insurance_count > 0) {
                        // Insurance expand collapse widget
                        $widgetTitle = xl("Insurance");
                        $widgetLabel = "insurance";
                        $widgetButtonLabel = xl("Edit");
                        $widgetButtonLink = "demographics_full.php";
                        $widgetButtonClass = "";
                        $linkMethod = "html";
                        $icon = "icon-check";
                        $bodyClass = "";
                        $widgetAuth = ($thisauth == "write");
                        $fixedWidth = true;
                        expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);

                        if ($insurance_count > 0) {
                            ?>

                            <ul class="tabNav"><?php
                                ///////////////////////////////// INSURANCE SECTION
                                $first = true;
                                foreach (array('primary', 'secondary', 'tertiary') as $instype) {

                                    $query = "SELECT * FROM insurance_data WHERE " .
                                            "pid = ? AND type = ? " .
                                            "ORDER BY date DESC";
                                    $res = sqlStatement($query, array($pid, $instype));

                                    $enddate = 'Present';

                                    while ($row = sqlFetchArray($res)) {
                                        if ($row['provider']) {

                                            $ins_description = ucfirst($instype);
                                            $ins_description = xl($ins_description);
                                            $ins_description .= strcmp($enddate, 'Present') != 0 ? " (" . xl('Old') . ")" : "";
                                            ?>
                                            <li <?php echo $first ? 'class="current"' : '' ?>><a href="/play/javascript-tabbed-navigation/">
                                                    <?php echo htmlspecialchars($ins_description, ENT_NOQUOTES); ?></a></li>
                                            <?php
                                            $first = false;
                                        }
                                        $enddate = $row['date'];
                                    }
                                }
                                // Display the eligibility tab
                                echo "<li><a href='/play/javascript-tabbed-navigation/'>" .
                                htmlspecialchars(xl('Eligibility'), ENT_NOQUOTES) . "</a></li>";
                                ?></ul><?php }
                            ?>

                        <div class="tabContainer">
                            <?php
                            $first = true;
                            foreach (array('primary', 'secondary', 'tertiary') as $instype) {
                                $enddate = 'Present';

                                $query = "SELECT * FROM insurance_data WHERE " .
                                        "pid = ? AND type = ? " .
                                        "ORDER BY date DESC";
                                $res = sqlStatement($query, array($pid, $instype));
                                while ($row = sqlFetchArray($res)) {
                                    if ($row['provider']) {
                                        ?>
                                        <div class="tab <?php echo $first ? 'current' : '' ?>">
                                            <table border='0' cellpadding='0' width='100%'>
                                                <?php
                                                $icobj = new InsuranceCompany($row['provider']);
                                                $adobj = $icobj->get_address();
                                                $insco_name = trim($icobj->get_name());
                                                ?>
                                                <tr>
                                                    <td valign='top' colspan='3'>
                                                        <span class='text'>
                                                            <?php if (strcmp($enddate, 'Present') != 0) echo htmlspecialchars(xl("Old"), ENT_NOQUOTES) . " "; ?>
                                                            <?php
                                                            $tempinstype = ucfirst($instype);
                                                            echo htmlspecialchars(xl($tempinstype . ' Insurance'), ENT_NOQUOTES);
                                                            ?>
                                                            <?php if (strcmp($row['date'], '0000-00-00') != 0) { ?>
                                                                <?php echo htmlspecialchars(xl('from', '', ' ', ' ') . $row['date'], ENT_NOQUOTES); ?>
                                                            <?php } ?>
                                                            <?php
                                                            echo htmlspecialchars(xl('until', '', ' ', ' '), ENT_NOQUOTES);
                                                            echo (strcmp($enddate, 'Present') != 0) ? $enddate : htmlspecialchars(xl('Present'), ENT_NOQUOTES);
                                                            ?>:</span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td valign='top'>
                                                        <span class='text'>
                                                            <?php
                                                            if ($insco_name) {
                                                                echo htmlspecialchars($insco_name, ENT_NOQUOTES) . '<br>';
                                                                if (trim($adobj->get_line1())) {
                                                                    echo htmlspecialchars($adobj->get_line1(), ENT_NOQUOTES) . '<br>';
                                                                    echo htmlspecialchars($adobj->get_city() . ', ' . $adobj->get_state() . ' ' . $adobj->get_zip(), ENT_NOQUOTES);
                                                                }
                                                            } else {
                                                                echo "<font color='red'><b>" . htmlspecialchars(xl('Unassigned'), ENT_NOQUOTES) . "</b></font>";
                                                            }
                                                            ?>
                                                            <br>
                                                            <?php echo htmlspecialchars(xl('Policy Number'), ENT_NOQUOTES); ?>: 
                                                            <?php echo htmlspecialchars($row['policy_number'], ENT_NOQUOTES) ?><br>
                                                            <?php echo htmlspecialchars(xl('Plan Name'), ENT_NOQUOTES); ?>: 
                                                            <?php echo htmlspecialchars($row['plan_name'], ENT_NOQUOTES); ?><br>
                                                            <?php echo htmlspecialchars(xl('Group Number'), ENT_NOQUOTES); ?>: 
                <?php echo htmlspecialchars($row['group_number'], ENT_NOQUOTES); ?></span>
                                                    </td>
                                                    <td valign='top'>
                                                        <span class='bold'><?php echo htmlspecialchars(xl('Subscriber'), ENT_NOQUOTES); ?>: </span><br>
                                                        <span class='text'><?php echo htmlspecialchars($row['subscriber_fname'] . ' ' . $row['subscriber_mname'] . ' ' . $row['subscriber_lname'], ENT_NOQUOTES); ?>
                                                            <?php
                                                            if ($row['subscriber_relationship'] != "") {
                                                                echo "(" . htmlspecialchars($row['subscriber_relationship'], ENT_NOQUOTES) . ")";
                                                            }
                                                            ?>
                                                            <br>
                                                            <?php echo htmlspecialchars(xl('S.S.'), ENT_NOQUOTES); ?>: 
                                                            <?php echo htmlspecialchars($row['subscriber_ss'], ENT_NOQUOTES); ?><br>
                                                            <?php echo htmlspecialchars(xl('D.O.B.'), ENT_NOQUOTES); ?>:
                                                            <?php if ($row['subscriber_DOB'] != "0000-00-00 00:00:00") echo htmlspecialchars($row['subscriber_DOB'], ENT_NOQUOTES); ?><br>
                                                            <?php echo htmlspecialchars(xl('Phone'), ENT_NOQUOTES); ?>: 
                <?php echo htmlspecialchars($row['subscriber_phone'], ENT_NOQUOTES); ?>
                                                        </span>
                                                    </td>
                                                    <td valign='top'>
                                                        <span class='bold'><?php echo htmlspecialchars(xl('Subscriber Address'), ENT_NOQUOTES); ?>: </span><br>
                                                        <span class='text'><?php echo htmlspecialchars($row['subscriber_street'], ENT_NOQUOTES); ?><br>
                                                            <?php echo htmlspecialchars($row['subscriber_city'], ENT_NOQUOTES); ?>
                                                            <?php if ($row['subscriber_state'] != "") echo ", "; echo htmlspecialchars($row['subscriber_state'], ENT_NOQUOTES); ?>
                                                            <?php if ($row['subscriber_country'] != "") echo ", "; echo htmlspecialchars($row['subscriber_country'], ENT_NOQUOTES); ?>
                                                        <?php echo " " . htmlspecialchars($row['subscriber_postal_code'], ENT_NOQUOTES); ?></span>

                <?php if (trim($row['subscriber_employer'])) { ?>
                                                            <br><span class='bold'><?php echo htmlspecialchars(xl('Subscriber Employer'), ENT_NOQUOTES); ?>: </span><br>
                                                            <span class='text'><?php echo htmlspecialchars($row['subscriber_employer'], ENT_NOQUOTES); ?><br>
                                                                <?php echo htmlspecialchars($row['subscriber_employer_street'], ENT_NOQUOTES); ?><br>
                                                                <?php echo htmlspecialchars($row['subscriber_employer_city'], ENT_NOQUOTES); ?>
                                                                <?php if ($row['subscriber_employer_city'] != "") echo ", "; echo htmlspecialchars($row['subscriber_employer_state'], ENT_NOQUOTES); ?>
                                                                <?php if ($row['subscriber_employer_country'] != "") echo ", "; echo htmlspecialchars($row['subscriber_employer_country'], ENT_NOQUOTES); ?>
                                                            <?php echo " " . htmlspecialchars($row['subscriber_employer_postal_code'], ENT_NOQUOTES); ?>
                                                            </span>
                <?php } ?>

                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                <?php if ($row['copay'] != "") { ?>
                                                            <span class='bold'><?php echo htmlspecialchars(xl('CoPay'), ENT_NOQUOTES); ?>: </span>
                                                            <span class='text'><?php echo htmlspecialchars($row['copay'], ENT_NOQUOTES); ?></span>
                                                            <br />
                <?php } ?>
                                                        <span class='bold'><?php echo htmlspecialchars(xl('Accept Assignment'), ENT_NOQUOTES); ?>:</span>
                                                        <span class='text'><?php if ($row['accept_assignment'] == "TRUE") echo xl("YES"); ?>
                                                        <?php if ($row['accept_assignment'] == "FALSE") echo xl("NO"); ?></span>
                <?php if (!empty($row['policy_type'])) { ?>
                                                            <br />
                                                            <span class='bold'><?php echo htmlspecialchars(xl('Secondary Medicare Type'), ENT_NOQUOTES); ?>: </span>
                                                            <span class='text'><?php echo htmlspecialchars($policy_types[$row['policy_type']], ENT_NOQUOTES); ?></span>
                <?php } ?>
                                                    </td>
                                                    <td valign='top'></td>
                                                    <td valign='top'></td>
                                                </tr>

                                            </table>
                                        </div>
                                        <?php
                                    } // end if ($row['provider'])
                                    $enddate = $row['date'];
                                    $first = false;
                                } // end while
                            } // end foreach
                            // Display the eligibility information
                            echo "<div class='tab'>";
                            show_eligibility_information($pid, true);
                            echo "</div>";
                            ?>
                        </div>

<?php } //   ?>
                    <!--///////////////////////////////// END INSURANCE SECTION-->

                    <!--Notas-->
                    <div class="accordion-item">
                        <?php
                        $widgetTitle = xl("Notes");
                        $widgetLabel = "pnotes";
                        $widgetButtonLabel = xl("Edit");
                        $widgetButtonLink = "../patient_file/summary/pnotes_full.php?form_active=1";
                        $widgetButtonClass = "iframe";
                        $linkMethod = "html";
                        $icon = "icon-book";
                        $bodyClass = "notab";
                        $widgetAuth = true;
                        $fixedWidth = true;
                        expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);
                        ?>
                    </div>
                </div>			

                <!--Recordatorios del paciente-->
                <?php
               /* if ((acl_check('patients', 'med')) && ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_prw'])) {
                    echo "<div class='accordion-item'>";
                    $widgetTitle = xl("Patient Reminders");
                    $widgetLabel = "patient_reminders";
                    $widgetButtonLabel = xl("Edit");
                    $widgetButtonLink = "../patient_file/reminder/patient_reminders.php?mode=simple&patient_id=" . $pid;
                    $widgetButtonClass = "iframe";
                    $linkMethod = "html";
                    $icon = "icon-calendar";
                    $bodyClass = "notab";
                    $widgetAuth = true;
                    $fixedWidth = true;
                    expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);
                    ?>
					</div>
				</div>
				<?php } */?>

        <!--Publicaciones-->
        <div class="accordion-item">
            <?php
            // disclosures expand collapse widget
            $widgetTitle = xl("Disclosures");
            $widgetLabel = "disclosures";
            $widgetButtonLabel = xl("Edit");
            $widgetButtonLink = "../patient_file/summary/disclosure_full.php";
            $widgetButtonClass = "iframe";
            $linkMethod = "html";
            $bodyClass = "notab";
            $icon = "icon-tasks";
            $widgetAuth = true;
            $fixedWidth = true;
            expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);
            ?>
        </div>
    </div>

    <!--Constantes Vitales-->
        <?php if ($vitals_is_registered && acl_check('patients', 'med')) { ?>
        <div class="accordion-item">			
            <?php
            // vitals expand collapse widget
            $widgetTitle = xl("Vitals");
            $widgetLabel = "vitals";
            $widgetButtonLabel = xl("Trend");
            $widgetButtonLink = "../encounter/trend_form.php?formname=vitals";
            $widgetButtonClass = "";
            $linkMethod = "html";
            $icon = "icon-bar-chart";
            $bodyClass = "notab";
            // check to see if any vitals exist
            $existVitals = sqlQuery("SELECT * FROM form_vitals WHERE pid=?", array($pid));
            if ($existVitals) {
                $widgetAuth = true;
            } else {
                $widgetAuth = false;
            }
            $fixedWidth = true;
            expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);
            ?>
        </div>
    </div>
<?php } ?>

<?php
// This generates a section similar to Vitals for each LBF form that
// supports charting.  The form ID is used as the "widget label".
//
$gfres = sqlStatement("SELECT option_id, title FROM list_options WHERE " .
        "list_id = 'lbfnames' AND option_value > 0 ORDER BY seq, title");
while ($gfrow = sqlFetchArray($gfres)) {
    ?>
    <tr>
        <td >
            <?php
            // vitals expand collapse widget
            $vitals_form_id = $gfrow['option_id'];
            $widgetTitle = $gfrow['title'];
            $widgetLabel = $vitals_form_id;
            $widgetButtonLabel = xl("Trend");
            $widgetButtonLink = "../encounter/trend_form.php?formname=$vitals_form_id";
            $widgetButtonClass = "";
            $linkMethod = "html";
            $bodyClass = "notab";
            // check to see if any instances exist for this patient
            $existVitals = sqlQuery(
                    "SELECT * FROM forms WHERE pid = ? AND formdir = ? AND deleted = 0", array($pid, $vitals_form_id));
            $widgetAuth = $existVitals ? true : false;
            $fixedWidth = true;
            expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth);
            ?>
        </div> <!-- This is required by expand_collapse_widget(). -->
    </td>
    </tr>
    <?php
} // end while
?>

<!--Facturacion-->
<div class="accordion-item">
    <?php
    $widgetTitle = xl("Billing");
    $widgetLabel = "billing";
    $widgetButtonLabel = xl("Edit");
    $widgetButtonLink = "return newEvt();";
    $widgetButtonClass = "";
    $linkMethod = "javascript";
    $bodyClass = "notab";
    $widgetAuth = false;
    $fixedWidth = true;
    $icon = "icon-credit-card";
    expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);
    ?>

    <?php
    if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
        // Show current balance and billing note, if any.
        echo "        <div style='margin-left: 10px; margin-right: 10px'>" .
        "<span class='bold'><font color='#ee6600'>" .
        htmlspecialchars(xl('Balance Due'), ENT_NOQUOTES) .
        ": " . htmlspecialchars(oeFormatMoney(get_patient_balance($pid)), ENT_NOQUOTES) .
        "</font></span><br>";
        if ($result['genericname2'] == 'Billing') {
            echo "<span class='bold'><font color='red'>" .
            htmlspecialchars(xl('Billing Note'), ENT_NOQUOTES) . ":" .
            htmlspecialchars($result['genericval2'], ENT_NOQUOTES) .
            "</font></span><br>";
        }
        if ($result3['provider']) {   // Use provider in case there is an ins record w/ unassigned insco
            echo "<span class='bold'>" .
            htmlspecialchars(xl('Primary Insurance'), ENT_NOQUOTES) . ': ' . htmlspecialchars($insco_name, ENT_NOQUOTES) .
            "</span>&nbsp;&nbsp;&nbsp;";
            if ($result3['copay'] > 0) {
                echo "<span class='bold'>" .
                htmlspecialchars(xl('Copay'), ENT_NOQUOTES) . ': ' . htmlspecialchars($result3['copay'], ENT_NOQUOTES) .
                "</span>&nbsp;&nbsp;&nbsp;";
            }
            echo "<span class='bold'>" .
            htmlspecialchars(xl('Effective Date'), ENT_NOQUOTES) . ': ' . htmlspecialchars(oeFormatShortDate($result3['effdate'], ENT_NOQUOTES)) .
            "</span>";
        }
        echo "</div><br>";
    }
    ?>

</div>
</div>	

</div>
<!-- end accordion div -->
</div>
<!-- end left column div -->

<!------------------------------------------------ start right column div ------------------------------------------>
<div id="column_right">
    <div id="patient" class="border">
        <div id="patient_gnl">
            <div style="float: left; margin-left: 4px; border: 1px solid rgb(228, 227, 227);">
                <?php
                $tmp = pic_array();
                echo $tmp[0];
                ?>
            </div>
            <div style="float: right;width: 120px;">
                <p style="padding: 0px; font-size: 15px; margin-top: 0px; color: rgb(162, 162, 162);">
                    <span style="color: rgb(67, 172, 164); font-weight: 500; font-size: 15px;"><?php echo htmlspecialchars($result['fname'] . " " . $result['lname'] . " " . $result['lname2'], ENT_NOQUOTES); ?></span><br/>
                    <?php
                    echo "<b style='font-size: 12px;'>";
                    $date = new DateTime($result['DOB']);
                    echo $date->format('d/m/Y') . "</b><br/><span style='font-size: 11px;'>(FEC NAC)</span><br/>";

                    if ($result['country_code'] != '') {
                        echo "<b style='font-size: 12px;'>" . $result['country_code'] . "</b></br><span style='font-size: 11px;'>(PAIS)</span><br/>";
                    }
                    ?>

                </p>
            </div>
        </div>
        <div class="patient_info_left">
            <a title="Editar" href="../patient_file/summary/demographics_full.php" class="css_button_small iframe"><i class="icon-edit"></i></a>
			<h2>GENERAL</h2>
            <p>
                SEXO: <span><?php
                    if ($result['sex'] == "Female") {
                        echo "Femenino";
                    } else {
                        echo "Masculino";
                    }
                    ?></span><br/>
                <?php
                if ($result['email'] != '') {
                    ?>
                    EMAIL1: <span><?php echo $result['email']; ?></span>
                    <?php
                }
                ?>
            </p>
        </div>
        <div class="patient_info_left">
            <h2>DIRECCION</h2>
            <p>
<?php echo $result['street']; ?>
            </p>
        </div>
        <div class="patient_info_left">
            <h2>TELEFONO</h2>
            <ul>
                <?php
                if ($result['phone_home'] != '') {
                    echo "<li>" . $result['phone_home'] . " (# CASA)</li>";
                }

                if ($result['phone_cell'] != '') {
                    echo "<li>" . $result['phone_cell'] . " (# CEL)</li>";
                }
                ?>
            </ul>
        </div>
    </div>
    <div>
        <!--// Advance Directives-->
        <?php
        if ($GLOBALS['advance_directives_warning']) {
            // advance directives expand collapse widget
            $widgetTitle = xl("Advance Directives");
            $widgetLabel = "directives";
            $widgetButtonLabel = xl("Edit");
            $widgetButtonLink = "return advdirconfigure();";
            $widgetButtonClass = "";
            $linkMethod = "javascript";
            $bodyClass = "summary_item small";
            $widgetAuth = true;
            $fixedWidth = false;
            $icon = "";
            expand_collapse_widget($widgetTitle, $widgetLabel, $widgetButtonLabel, $widgetButtonLink, $widgetButtonClass, $linkMethod, $bodyClass, $widgetAuth, $fixedWidth, $icon);
            $counterFlag = false; //flag to record whether any categories contain ad records
            $query = "SELECT id FROM categories WHERE name='Advance Directive'";
            $myrow2 = sqlQuery($query);
            if ($myrow2) {
                $parentId = $myrow2['id'];
                $query = "SELECT id, name FROM categories WHERE parent=?";
                $resNew1 = sqlStatement($query, array($parentId));
                while ($myrows3 = sqlFetchArray($resNew1)) {
                    $categoryId = $myrows3['id'];
                    $nameDoc = $myrows3['name'];
                    $query = "SELECT documents.date, documents.id " .
                            "FROM documents " .
                            "INNER JOIN categories_to_documents " .
                            "ON categories_to_documents.document_id=documents.id " .
                            "WHERE categories_to_documents.category_id=? " .
                            "AND documents.foreign_id=? " .
                            "ORDER BY documents.date DESC";
                    $resNew2 = sqlStatement($query, array($categoryId, $pid));
                    $limitCounter = 0; // limit to one entry per category
                    while (($myrows4 = sqlFetchArray($resNew2)) && ($limitCounter == 0)) {
                        $dateTimeDoc = $myrows4['date'];
                        // remove time from datetime stamp
                        $tempParse = explode(" ", $dateTimeDoc);
                        $dateDoc = $tempParse[0];
                        $idDoc = $myrows4['id'];
                        echo "<a href='$web_root/controller.php?document&retrieve&patient_id=" .
                        htmlspecialchars($pid, ENT_QUOTES) . "&document_id=" .
                        htmlspecialchars($idDoc, ENT_QUOTES) . "&as_file=true'>" .
                        htmlspecialchars(xl_document_category($nameDoc), ENT_NOQUOTES) . "</a> " .
                        htmlspecialchars($dateDoc, ENT_NOQUOTES);
                        echo "<br>";
                        $limitCounter = $limitCounter + 1;
                        $counterFlag = true;
                    }
                }
            }
            if (!$counterFlag) {
                echo "&nbsp;&nbsp;" . htmlspecialchars(xl('None'), ENT_NOQUOTES);
            }
            ?>
        </div>
<?php } ?> 

    <!--/ Citas-->
    <?php
    if (isset($pid) && !$GLOBALS['disable_calendar']) {
        $query = "SELECT e.pc_eid, e.pc_aid, e.pc_title, e.pc_eventDate, " .
                "e.pc_startTime, e.pc_hometext, u.fname, u.lname, u.mname, " .
                "c.pc_catname " .
                "FROM openemr_postcalendar_events AS e, users AS u, " .
                "openemr_postcalendar_categories AS c WHERE " .
                "e.pc_pid = ? AND e.pc_eventDate >= CURRENT_DATE AND " .
                "u.id = e.pc_aid AND e.pc_catid = c.pc_catid " .
                "ORDER BY e.pc_eventDate, e.pc_startTime";
        $res = sqlStatement($query, array($pid));
        echo '<div class="patient_secondary" id="citas">';
        $widgetTitle = xl("Appointments");
        $widgetLabel = "appointments";
        $widgetButtonLabel = xl("Add");
        $widgetButtonLink = "return newEvt();";
        $url = "<a href='#' class='addIcon iframe css_button_left' id='" . $widgetLabel . "' onclick='" . $widgetButtonLink . "' title='" .
                htmlspecialchars($widgetButtonLabel, ENT_NOQUOTES) . "'><i class='icon-plus-sign'></i></a>";
        $widgetButtonLink = "return newEvt();";
        if (sqlNumRows($res) > 0) {
            echo "<h2>" . xl("Appointments") . " <span style='float: right; background-color: rgb(228, 228, 228); border-radius: 5px 5px 5px 5px; border-right: 1px solid rgb(204, 204, 204); border-width: 2px 1px 1px; border-style: solid; border-color: -moz-use-text-color rgb(204, 204, 204) rgb(204, 204, 204); -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; padding: 0px 10px;'> " . sqlNumRows($res) . " </span>" . $url . "</h2>";
            ?>
            <ul>
                <?php
                $count = 0;
                while ($row = sqlFetchArray($res)) {
                    ?>
                    <li>
                        <p>
                            <span class="title"><?php echo htmlspecialchars($row['title'], ENT_NOQUOTES); ?></span><br/>
                            <span class="desc">
                                <?php
                                $count++;
                                $dayname = date("l", strtotime($row['pc_eventDate']));
                                $dispampm = "am";
                                $disphour = substr($row['pc_startTime'], 0, 2) + 0;
                                $dispmin = substr($row['pc_startTime'], 3, 2);
                                if ($disphour >= 12) {
                                    $dispampm = "pm";
                                    if ($disphour > 12)
                                        $disphour -= 12;
                                }
                                $etitle = xl('(Click to edit)');
                                if ($row['pc_hometext'] != "") {
                                    $etitle = xl('Comments') . ": " . ($row['pc_hometext']) . "\r\n" . $etitle;
                                }
                                echo "<a href='javascript:oldEvt(" . htmlspecialchars($row['pc_eid'], ENT_QUOTES) .
                                ")' title='" . htmlspecialchars($etitle, ENT_QUOTES) . "'>";
                                echo "<b>" . htmlspecialchars(xl($dayname) . ", " . $row['pc_eventDate'], ENT_NOQUOTES) . "</b><br>";
                                echo htmlspecialchars("$disphour:$dispmin " . xl($dispampm) . " " . xl_appt_category($row['pc_catname']), ENT_NOQUOTES) . "<br>\n";
                                echo htmlspecialchars($row['fname'] . " " . $row['lname'], ENT_NOQUOTES) . "</a><br>\n";
                                //echo htmlspecialchars( $row['date'],ENT_NOQUOTES)."</br>";
                                ?>
                            </span>
                        </p>
                    </li>
                    <?php
                }
                echo "</ul>";
            } else {
                echo "<h2>" . xl("Appointments") . " <span style='float: right; background-color: rgb(228, 228, 228); border-radius: 5px 5px 5px 5px; border-right: 1px solid rgb(204, 204, 204); border-width: 2px 1px 1px; border-style: solid; border-color: -moz-use-text-color rgb(204, 204, 204) rgb(204, 204, 204); -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; padding: 0px 10px;'> " . sqlNumRows($res) . " </span>" . $url . "</h2>";

                //echo "<ul><li><p>No se han ingresado citas.</p></li></ul>";
            }
        }
        echo "</div>";
        ?>

        <!-- Problemas med, alergias, med, vacunas-->
        <div id='stats_div'></div>

        <!-- Recordatorios clinicos-->
        <?php
        /*if ((acl_check('patients', 'med')) && ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_crw'])) {
            // clinical summary expand collapse widget
            echo '<div class="patient_secondary" id="' . xl("Clinical Reminders") . '">';
            $widgetButtonLink = "../patient_file/reminder/clinical_reminders.php?patient_id=" . $pid;
            echo "<h2>" . xl("Clinical Reminders");
            echo "<a class='addIcon iframe css_button_left' title='" . htmlspecialchars(xl('Edit'), ENT_NOQUOTES) . "' href='" . $widgetButtonLink . "'>";
            echo '<i class="icon-plus-sign"></i>';
            echo "</a></h2>";

            echo '<div class="summary_item small patient_secondary" 7px;="" padding:="" id="clinical_reminders_ps_expand"></div>';
            echo "</div>";
        } // end if crw*/
        ?>
</div> 
<!-- end right column div -->

</div> <!-- end main content div -->
</div> <!-- main -->
</body>
</html>